package com.webserver.core;

import com.webserver.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServletContext {
    private static Map<String, HttpServlet>servletMapping = new HashMap<>();

    static {
        initServletMapping();
    }

    private static void initServletMapping(){
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read("./conf/servlet.xml");
            Element root = doc.getRootElement();
            List<Element>list = root.elements("servlet");
            for (Element e:list){
                String key = e.attributeValue("path");
                String value = e.attributeValue("className");
                Class cls = Class.forName(value);
                Object o = cls.newInstance();
                servletMapping.put(key,(HttpServlet)o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static HttpServlet  getServlet(String key){
        return servletMapping.get(key);
    }

//    public static void main(String[] args) {
//        System.out.println(servletMapping.size());
//    }
}
